package com.duguo.dynamicmvc.demo.accounts;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.duguo.dynamicmvc.model.Model;
import com.duguo.dynamicmvc.view.redirect.RedirectToRefererView;
import com.duguo.dynamicmvc.view.redirect.RedirectToRootView;

public class LogoutView extends RedirectToRootView{
	
	private Pattern _protectedUrlPattern;
	private Pattern _redirectFilter=Pattern.compile(".*(/do[A-Z]).*");

    public void render(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {    	
    	String targetUrl = RedirectToRefererView.getReferer(request);
    	if(isAllowedToAccess(targetUrl))
    		senRedirect(request, response, model,targetUrl);
    	else{
    		super.render(request, response, model);
    	}
    }

	private boolean isAllowedToAccess(String targetUrl) {
		return targetUrl!=null && !_redirectFilter.matcher(targetUrl).find() && 
		(_protectedUrlPattern==null || !_protectedUrlPattern.matcher(targetUrl).find());
	}

	public void setProtectedUrlPattern(String protectedUrlPattern) {
		_protectedUrlPattern = Pattern.compile(protectedUrlPattern);
	}

	public void setRedirectFilter(String redirectFilter) {
		_redirectFilter = Pattern.compile(redirectFilter);
	}
}
